package com.bruce.practice.design.strategy;

import org.apache.commons.collections4.CollectionUtils;
import org.reflections.Reflections;
import org.reflections.scanners.SubTypesScanner;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;

import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author luotuan
 * @Description 税收工厂类
 * @create 2020-05-03 11:09
 **/
public class TaxStrategyFactory {
    private static ConcurrentHashMap<TaxType, TaxStrategy> taxMap = new ConcurrentHashMap<>();

    static {
        register();
    }

    public static TaxStrategy getTaxStrategy(TaxType taxType) {
        if (taxMap.containsKey(taxType)) {
            return taxMap.get(taxType);
        }else{
            throw new RuntimeException("没有匹配的税收策略");
        }
    }

    /**
     * 注册
     */
    public static void register() {
        try {
            Reflections reflections = new Reflections(new ConfigurationBuilder()
                    .setUrls(ClasspathHelper.forPackage(TaxStrategy.class.getPackage().getName())).setScanners(new SubTypesScanner()));
            Set<Class<? extends TaxStrategy>> taxStrategySet = reflections.getSubTypesOf(TaxStrategy.class);
            if (CollectionUtils.isNotEmpty(taxStrategySet)) {
                for (Class<?> clazz : taxStrategySet) {
                    if (clazz.isAnnotationPresent(TaxTypeAnnotation.class)) {
                        TaxTypeAnnotation taxTypeAnnotation = clazz.getAnnotation(TaxTypeAnnotation.class);
                        TaxType taxType = taxTypeAnnotation.taxType();
                        taxMap.put(taxType, (TaxStrategy) clazz.newInstance());
                    }
                }
            }
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
